package com.anche.demo.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.Map;

/**
 * 创建Handler，设置excel中的下拉框
 *
 * @author zengj
 * @date 2022/11/24 10:41
 */
@Data
@AllArgsConstructor
public class SelectedSheetWriteHandler implements SheetWriteHandler {

    /**
     * Called before create the sheet
     */
    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }

    /**
     * Called after the sheet is created
     */
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 这里可以对cell进行任何操作
        Sheet sheet = writeSheetHolder.getSheet();
        DataValidationHelper helper = sheet.getDataValidationHelper();
            // 设置下拉列表的行： 首行，末行，首列，末列
            CellRangeAddressList rangeList = new CellRangeAddressList(0, 65535, 2, 2);
            // 设置下拉列表的值
                    String[] ss=new String[2];
            ss[0]="张三";
            ss[1]="李四";
            DataValidationConstraint constraint = helper.createExplicitListConstraint(ss);
            // 设置约束
            DataValidation validation = helper.createValidation(constraint, rangeList);
            // 阻止输入非下拉选项的值
            validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
            // 是否弹错误提示框
            validation.setShowErrorBox(true);
            validation.setSuppressDropDownArrow(true);
            // 错误提示框内容
            validation.createErrorBox("提示", "请输入下拉选项中的内容");
            // 添加约束
            sheet.addValidationData(validation);
    }
}
